package com.yyfax.ph.personal.authority.changepassword;

import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.personal.authority.RSAPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ChangePasswordPresenter extends RSAPresenter<ChangePasswordModel, ChangePasswordPresenter.View> {
	private static final String TAG = ChangePasswordPresenter.class.getSimpleName();
	private View mView;

	public static class Generator implements PresenterFactory<ChangePasswordPresenter> {
		@Override
		public ChangePasswordPresenter create() {
			return new ChangePasswordPresenter();
		}
	}

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new ChangePasswordModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		ChangePasswordModel.ChangePwdParams getChangePwdParams();

		void changePasswordSuccess();

		void changePasswordFailure(String tips);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		ChangePasswordModel.ChangePwdParams changePwd = (ChangePasswordModel.ChangePwdParams) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		changePwd.password = RSA.encryptByPublicKey(changePwd.password, keyRSA);
		changePwd.newPassword = RSA.encryptByPublicKey(changePwd.newPassword, keyRSA);
		return changePwd;
	}

	public void changePassword() {
		execute(mView.getChangePwdParams());
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void ChangePwdResult(ChangePasswordModel.ChangePwdResult changePwdResult) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E021, changePwdResult.getStatus());
		if (isResponseSuccess(changePwdResult)) {
			mView.changePasswordSuccess();
		} else {
			mView.changePasswordFailure(changePwdResult.getMsg());
		}
	}

}
